package org.adream.account.service;

import java.io.File;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.adream.account.dao.TagDao;
import org.adream.account.dao.UserDao;
import org.adream.account.dao.UserDetailDao;
import org.adream.account.dao.UserTagLinkDao;
import org.adream.account.entity.TagEntity;
import org.adream.account.entity.UserDetailEntity;
import org.adream.account.entity.UserEntity;
import org.adream.account.model.ResultModel;
import org.adream.account.model.SynDream2020DataModel;
import org.adream.account.service.async.SynDream2020Service;
import org.adream.account.service.cloudCollege.SynCloudCollegeService;
import org.adream.account.service.cloudCollege.SynCloudCollegeUserEntity;
import org.adream.account.service.library.SynLibraryService;
import org.adream.account.service.library.SynLibraryUserEntity;
import org.adream.account.service.scfire.SynScFireService;
import org.adream.account.service.scfire.SynScFireUserEntity;
import org.adream.account.util.Constant;
import org.adream.account.util.IdGenerator;
import org.adream.account.util.UUIDUtil;
import org.adream.account.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
public class UserDetailService {
	
	private final static Logger logger = LoggerFactory.getLogger(UserDetailService.class);
	
	@Autowired
	private UserDetailDao userDetailDao;
	
	@Autowired  
	private HttpSession session;  

	@Autowired
	private UserTagLinkDao userTagLinkDao;
	
	@Autowired
	private TagDao tagDao;
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private SynDream2020Service synDream2020Service;
	
	@Autowired
	private SynScFireService synScFireService;
	
	@Autowired
	private SynLibraryService synLibraryService;
	
	@Autowired
	private SynCloudCollegeService synCloudCollegeService;
	
	@Value("${image.file.path.userpic}")
    private String userPicPath;  //用户图片
	
	@Value("${headimgurl.prefix}")
	private String headimgurlPrefix;
	
	/**
	 * 增
	 * @param userDetail
	 */
	public ResultModel<String> addUserDetail(UserDetailEntity userDetail) {
		String operator = (String)session.getAttribute("uid");
		userDetail.setCreator(operator);
		userDetail.setModifier(operator);
		userDetail.setDr(Constant.ONE);
		int result = userDetailDao.addUserDetail(userDetail);
		if(result == 0) {
			logger.warn("新增用户详情数据失败,数据库错误,uid:{}", userDetail.getUid());
			return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误,请联系系统管理员", null);
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}
	
	/**
	 * 删除   逻辑删除
	 * @param uid
	 */
	public ResultModel<String> deleteUserDetail(String uid) {
		UserDetailEntity userDetail = userDetailDao.queryUserDetailByDrAndUid(Constant.ONE, uid);
		if(userDetail == null) {
			logger.warn("删除用户详情数据失败,数据库错误,uid:{}", uid);
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "删除失败,数据不存在", null);
		} 
		String modifier = (String)session.getAttribute("uid");
		userDetail.setModifier(modifier);
		userDetail.setDr(Constant.ZERO);
		int result = userDetailDao.deleteUserDetail(userDetail);
		if(result == 0) {
			logger.warn("删除用户详情数据失败,数据库错误,uid:{}", uid);
			return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误,请联系系统管理员", null);
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}
	
	/**
	 * 更新
	 * @param userDetailEntity
	 * @throws ADreamServiceException
	 */
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=ADreamServiceException.class,isolation=Isolation.DEFAULT)
	public ResultModel<String> updateUserDetail(String uid,UserDetailEntity userDetailEntity) throws ADreamServiceException {
		UserDetailEntity userDetail = userDetailDao.queryUserDetailByUid(uid);
		if(userDetail == null){
			userDetailEntity.setUid(uid);
			userDetailEntity.setCreator(uid);
			userDetailEntity.setCts(new Date());
			userDetailEntity.setModifier(uid);
			userDetailEntity.setMts(new Date());
			userDetailEntity.setDr(Constant.ONE);
			int result = userDetailDao.replaceIntoUserDetail(userDetailEntity);
			if(result == 0) {
				return new ResultModel<String>(ResultModel.ERR_DATABASE, "系统错误,请联系系统管理员", null);
			}
		} else{
			String oriBankAccount = userDetail.getBankAccount();
			String oriPhone = userDetail.getPhone();
			Utils.copyPropertiesIgnoreNull(userDetailEntity, userDetail);
			//后台传入带*的之前账号
			if(oriPhone != null && Utils.replaceXing(oriPhone, 3, 4).equals(userDetailEntity.getPhone())) {
				userDetail.setPhone(oriPhone);
			}
			
			if(oriBankAccount != null && Utils.replaceXing(oriBankAccount,4,4).equals(userDetailEntity.getBankAccount())) {
				userDetail.setBankAccount(oriBankAccount);
			}
			userDetail.setUid(uid);
			userDetail.setModifier(uid);
			userDetail.setMts(new Date());
			userDetail.setDr(Constant.ONE);
			int result = userDetailDao.replaceIntoUserDetail(userDetail);
			if(result == 0) {
				return new ResultModel<String>(ResultModel.ERR_DATABASE, "系统错误,请联系系统管理员", null);
			}
		}
		
		if(userDetailEntity.getTagNames() != null) {
			userTagLinkDao.deleteUserTagLinkByUid(uid);   //先删除之前添加的标签
			String tagNames = userDetailEntity.getTagNames();
			//空格的字符\\s+
			//根据各种中英字符截取标签名
			String[] tagNameArray =tagNames.split("\\s+|[;；,，?？|.。:：!！-]");
			//去除重复标签
			Set<String> set = new HashSet<String>();
			for (int i = 0; i < tagNameArray.length; i++) {  
	            set.add(tagNameArray[i]);  
	        }  
			Object[] newTagNameArray = set.toArray();
			if(newTagNameArray!=null){
				int length = newTagNameArray.length;
				for(int i=0;i<length;i++){
					String tagName = (String)newTagNameArray[i];
					if(!StringUtils.isEmpty(tagName)){
						//校验标签是否存在
						TagEntity tag = tagDao.queryTagByTagName(tagName);
						//为空，不存在
						if(tag == null){
							tag = new TagEntity();
							tag.setTagName(tagName);
							tag.setTagId(IdGenerator.getGuid());
							tag.setTagWeight(1L);
							tag.setCreator(uid);
							tag.setCts(new Date());
							tag.setModifier(uid);
							tag.setMts(new Date());
							tag.setDr(Constant.ONE);
							tagDao.addTag(tag);  //先添加标签
						} else {
							//更新标签的权重
							if(tag.getTagWeight() == null) {
								tag.setTagWeight(1L);
							} else {
								if(tag.getTagWeight() + 1 >= Constant.MAX_TAG_WEIGHT) {
									tag.setTagWeight(Constant.MAX_TAG_WEIGHT);
								} else {
									tag.setTagWeight(tag.getTagWeight() + 1);
								}
							}
							tag.setModifier(uid);
							tag.setMts(new Date(System.currentTimeMillis()));
							tagDao.updateWeight(tag);
							
						}
						userTagLinkDao.replaceUserTag(uid, tag.getTagId());
					}
				}
			}
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}
	
	/**
	 * 更新用户头像
	 * 当前头像存放在acc_user中,曾使用的头像存放在acc_user_detail
	 * @param userDetailEntity
	 * @param request
	 * @throws ADreamServiceException
	 */
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=ADreamServiceException.class,isolation=Isolation.DEFAULT)
	public boolean updatePhoto(String uid,String base64url,Integer x,Integer y,Integer width,Integer height,String photo) throws ADreamServiceException {
		logger.info("更新用户头像");
		if(StringUtils.isEmpty(uid) || StringUtils.isEmpty(base64url)) {
			throw new ADreamServiceException("更新失败,请求参数为空");
		}
		UserDetailEntity userDetail = userDetailDao.queryUserDetailByUid(uid);
		
		String path = userPicPath.endsWith(File.separator) ? userPicPath : userPicPath + File.separator;
		File file = new File(path);
		if(!file.exists()) {
			file.mkdirs();
		}
		String fileName = null;
		
		if(base64url.startsWith(Constant.PART_BEGIN_BASE64URL)) {
			String ext = base64url.substring(base64url.indexOf("/") + 1,base64url.indexOf(";"));
			if("jpeg".equals(ext)) {
				ext = "jpg";
			}
			fileName = Utils.parseDateToYearMonthDay(new Date()) + "-" + UUIDUtil.createUUID() + "." + ext;
			if(!Utils.generateImage(base64url, path + fileName)) {
				return false;
			}
			if(!Utils.cutImage(path + fileName, x, y, width, height)) {
				return false;
			}
		} else {
			fileName = photo;
		}
		
		if(!StringUtils.isEmpty(fileName)) {
			if(userDetail == null) {
				userDetail = new UserDetailEntity();
				userDetail.setUid(uid);
				userDetail.setCreator(uid);
				userDetail.setCts(new Date());
				userDetail.setModifier(uid);
				userDetail.setMts(new Date());
				userDetail.setDr(Constant.ONE);
				userDetailDao.addUserDetail(userDetail);
			} else {
				String oriPhoto = userDetail.getUser().getHeadimgurl();
				if(StringUtils.isEmpty(oriPhoto) || !oriPhoto.equals(fileName)) {
					String photo1 = userDetail.getPhoto1();
					String photo2 = userDetail.getPhoto2();
					userDetail.setPhoto1(oriPhoto);
					userDetail.setPhoto2(photo1);
					userDetail.setPhoto3(photo2);
					userDetail.setModifier(uid);
					userDetail.setMts(new Date());
					userDetailDao.updatePhoto(userDetail);
				}
			}
			
			//更新user表中的headimgurl字段
			UserEntity user = userDao.queryUserByUid(uid);
			String oriHeadimgurl = "";
			if(user != null) {
				oriHeadimgurl = user.getHeadimgurl();
				user.setHeadimgurl(fileName);
				user.setModifier(uid);
				user.setMts(new Date());
				userDao.updateHeadimg(user);
			}
			
			//同步新版盒子数据
			SynDream2020DataModel data = new SynDream2020DataModel();
			data.setCasid(uid);
			String headimgurl =	headimgurlPrefix + uid;	//完整头像地址
			data.setAvatar(headimgurl);
			synDream2020Service.synDream2020Data(data);
			
			//同步火堆数据
			if(user != null) {				
				if(!StringUtils.isEmpty(user.getUnionid())) {
					SynScFireUserEntity scFireUser = new SynScFireUserEntity();
					scFireUser.setUnionid(user.getUnionid());
					scFireUser.setImage(headimgurl);
					synScFireService.synScFireUser(scFireUser);
				}
			}
			
			//同步梦想文库数据,真爱云学院
			//现头像与原来的头像不一致时执行同步操作
			if(!fileName.equals(oriHeadimgurl)) {
				SynLibraryUserEntity libraryUser = new SynLibraryUserEntity();
				libraryUser.setCasid(uid);
				libraryUser.setAvatar(headimgurl);
				synLibraryService.synLibraryUser(libraryUser);
				SynCloudCollegeUserEntity cloudCollegeUser = new SynCloudCollegeUserEntity();
				cloudCollegeUser.setCasId(uid);
				cloudCollegeUser.setHeadImgUrl(headimgurl);
				synCloudCollegeService.synLibraryUser(cloudCollegeUser);
			}
		}
		return true;
	}
	
	/**
	 * 查询
	 * @param uid
	 * @return
	 */
	public UserDetailEntity queryUserDetailByUid(String uid) {
		return userDetailDao.queryUserDetailByUid(uid);
	}
	
	/**
	 * 根据删除标志 	查询
	 * @param dr    删除标志
	 * @return
	 */
	public List<UserDetailEntity> queryUserDetailsByDr(int dr) {
		return userDetailDao.queryUserDetailsByDr(dr);
	}

	public ResultModel<String> updateBankInfo(String uid, String accountName, String bankAccount, String depositBank, String aopenBranch) {
		UserDetailEntity entity = userDetailDao.queryUserDetailByUid(uid);
		if(entity == null) {
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "更新失败,用户不存在", null);
		};
		// null时不更新
		accountName = (StringUtils.isEmpty(accountName) || StringUtils.isEmpty(accountName.trim())) ? null : accountName.trim();
		depositBank = (StringUtils.isEmpty(depositBank) || StringUtils.isEmpty(depositBank.trim())) ? null : depositBank.trim();
		bankAccount = (StringUtils.isEmpty(bankAccount) || StringUtils.isEmpty(bankAccount.trim())) ? null : bankAccount.trim();
		aopenBranch = (StringUtils.isEmpty(aopenBranch) || StringUtils.isEmpty(aopenBranch.trim())) ? null : aopenBranch.trim();
		
		entity.setAccountName(accountName);
		entity.setDepositBank(depositBank);
		entity.setBankAccount(bankAccount);
		entity.setAopenBranch(aopenBranch);
		entity.setModifier("huodui");
		entity.setMts(new Date());
		
		int result = userDetailDao.updateBankInfo(entity);
		if(result == 0) {
			return new ResultModel<String>(ResultModel.ERR_DATABASE, "系统错误,请联系系统管理员", null);
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}
}